import React, { Component } from 'react'
import { Card, Input, Button, Typography, Upload, message, Icon, DatePicker } from 'antd'
import moment from 'moment'
import memory from '../../../../utils/memory'
import './addResume.less'
import { reqAddResume, reqResumeListOne, reqResumeUpdate } from '../../../../api'
import { to } from '../../../../utils'
import config from '../../../../config'

const dateFormat = 'YYYY-MM-DD';
const { TextArea } = Input
const { Text } = Typography;
const { RangePicker } = DatePicker;
const itemInfo = {
    abilities: { key: '', detail: '' },
    experiences: { companyName: '', position: '', time: ['', ''], detail: '' },
    projects: { projectName: '', keyWord: [], detail: '' },
    demos: { demosName: '', subItem: [], detail: '' },
    edus: { school: '', time: ['', ''], degree: '' },
    certificates: { certificateName: '', time: '' }
}

const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
}

export default class AddResume extends Component {

    state = {
        name: '我的简历',
        username: '',
        userImg: '',
        basicInfo: {
            userInfo: [],
            intention: [],
            skills: [],
            resource: [],
        },
        selfAssessment: '',
        abilities: [],
        experiences: [],
        projects: [],
        demos: [],
        edus: [],
        certificates: [],
        wordUrl: '',
        pdfUrl: '',
        loading: false,
        _id: '0'
    }

    componentDidMount() {

        let _id = this.props.match.params._id
        if (_id !== '0') {
            reqResumeListOne(_id).then(res => {
                if (res.code !== 0) return message.error(res.msg)
                const { name, username, userImg, basicInfo, selfAssessment, abilities, experiences, projects, demos, edus, certificates, wordUrl, pdfUrl, _id } = res.body
                this.setState({ name, username, userImg, basicInfo, selfAssessment, abilities, experiences, projects, demos, edus, certificates, wordUrl, pdfUrl, _id })
            }).catch(err => {
                if (err) return console.log(err)
            })
        }
    }


    handleChange = info => {
        if (info.file.status === 'uploading') {
            this.setState({ loading: true });
            return;
        }
        if (info.file.status === 'done') {
            let res = info.file.response
            if (res.code !== 0) return message.error(res.msg)
            this.setState({
                userImg: res.body[0],
                loading: false,
            })
        }
    }

    handleNameChange = (e) => { this.setState({ name: e.target.value }) }
    handleUserameChange = (e) => { this.setState({ username: e.target.value }) }
    handleSelfAssessmentChange = (e) => { this.setState({ selfAssessment: e.target.value }) }
    handleWordUrlChange = (e) => { this.setState({ wordUrl: e.target.value }) }
    handlePdfUrlChange = (e) => { this.setState({ pdfUrl: e.target.value }) }

    addBasicInfoItem = (prop) => {
        let data = Object.assign({}, this.state.basicInfo, { [prop]: [...this.state.basicInfo[prop], { key: '', value: '' }] })
        this.setState({ basicInfo: data })
    }

    handleBasicInfoPropChange = (index, type, prop, e) => {
        let data = Object.assign({}, this.state.basicInfo)
        data[prop][index][type] = e.target.value
        this.setState({ basicInfo: data })
    }

    removeBasicInfoItem = (prop, index) => {
        let data = Object.assign({}, this.state.basicInfo)
        data[prop].splice(index, 1)
        this.setState({ basicInfo: data })
    }

    addItem = (prop) => {
        this.setState({ [prop]: [...this.state[prop], JSON.parse(JSON.stringify(itemInfo[prop]))] })
    }

    handleItemChange = (prop, index, key, e) => {
        let data = Object.assign([], this.state[prop])
        data[index][key] = e.target.value
        this.setState({ [prop]: data })
    }

    removeItem = (index, prop) => {
        let data = Object.assign([], this.state[prop])
        data.splice(index, 1)
        this.setState({ [prop]: data })
    }

    addProjectsKeyWord = (index) => {
        let data = Object.assign([], this.state.projects)
        data[index].keyWord.push('')
        this.setState({ projects: data })
    }

    handleProjectsKeyWordChange = (index, i, e) => {
        let data = Object.assign([], this.state.projects)
        data[index].keyWord[i] = e.target.value
        this.setState({ projects: data })
    }

    removeProjectsKeyWord = (index, i) => {
        let data = Object.assign([], this.state.projects)
        data[index].keyWord.splice(i, 1)
        this.setState({ projects: data })
    }

    // handleExperiencesTimeChage = (index, date) => {
    //     let data = Object.assign([], this.state.experiences)
    //     data[index].time = date
    //     console.log(data[index])
    //     this.setState({ experiences: data })
    // }
    handleExperiencesTimeChage2 = (index, i, e) => {
        let data = Object.assign([], this.state.experiences)
        data[index].time[i] = e.target.value
        this.setState({ experiences: data })
    }

    handleEdusTimeChage = (index, date) => {
        let data = Object.assign([], this.state.edus)
        data[index].time = date
        this.setState({ edus: data })
    }

    submit = async (status) => {
        let postData = {
            name: this.state.name,
            username: this.state.username,
            userImg: this.state.userImg,
            basicInfo: this.state.basicInfo,
            selfAssessment: this.state.selfAssessment,
            abilities: this.state.abilities,
            experiences: this.state.experiences,
            projects: this.state.projects,
            demos: this.state.demos,
            edus: this.state.edus,
            certificates: this.state.certificates,
            wordUrl: this.state.wordUrl,
            pdfUrl: this.state.pdfUrl,
            status,
        }
        if (this.state._id === '0') {
            let [err, res] = await to(reqAddResume(postData))
            if (err) return
            if (res.code !== 0) return message.error(res.msg)
            message.success(res.msg)
            setTimeout(() => {
                this.props.history.go(-1)
            }, 2000)
        } else {
            postData._id = this.state._id
            let [err, res] = await to(reqResumeUpdate(postData))
            if (err) return
            if (res.code !== 0) return message.error(res.msg)
            message.success(res.msg)
        }

    }

    render() {
        let { name, username, userImg, basicInfo, selfAssessment, abilities, experiences, projects, demos, edus, certificates, wordUrl, pdfUrl } = this.state
        const basicInfoPropName = { userInfo: '个人信息', intention: '求职意向', skills: '技能特长', resource: '相关资源(链接请写在@@之间,如@https://baidu.com@)' }
        const uploadButton = (
            <div>
                <Icon type={this.state.loading ? 'loading' : 'plus'} />
                <div className="ant-upload-text">上传头像</div>
            </div>
        )
        // const urlTip = '链接请用@@包裹，如@http://xxx.com@'
        const urlTip = ''

        return (
            <Card title="新增简历" style={{ height: '100%' }} className="addresume">
                <ul className="content">
                    <li className="name">
                        <div className="title">简历名称:</div>
                        <Input placeholder="请输入简历名称" value={name} onChange={this.handleNameChange} />
                    </li>
                    <li className="username">
                        <div className="title">姓名:</div>
                        <Input placeholder="请输入姓名" value={username} onChange={this.handleUserameChange} />
                    </li>
                    <li className="userImg">
                        <div className="title">头像:</div>
                        <Upload
                            name="files"
                            data={{ token: memory.user.token }}
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            action={config.host + "/file/normalUpload"}
                            beforeUpload={beforeUpload}
                            onChange={this.handleChange}
                        >
                            {userImg ? <img src={config.host + userImg} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                        </Upload>
                    </li>
                    <li className="basicInfo">
                        <div className="title">基本信息</div>
                        {
                            Object.keys(basicInfo).map((prop, i) => (
                                <div key={prop}>
                                    <div>{basicInfoPropName[prop]}<Button type="link" onClick={() => this.addBasicInfoItem(prop)}>新增选项</Button>{urlTip}</div>
                                    <ul>
                                        {basicInfo[prop].map((item, index) => (
                                            <li key={index} style={{ marginBottom: 10 }}>
                                                <Input placeholder={`请输入${basicInfoPropName[prop]}名`} value={item.key} style={{ width: 150 }} onChange={(e) => this.handleBasicInfoPropChange(index, 'key', prop, e)} />
                                                --
                                                <Input placeholder={`请输入${basicInfoPropName[prop]}值`} value={item.value} style={{ width: 500 }} onChange={(e) => this.handleBasicInfoPropChange(index, 'value', prop, e)} />
                                                <Button type="link" onClick={() => this.removeBasicInfoItem(prop, index)}>删除选项</Button>
                                            </li>
                                        ))}

                                    </ul>
                                </div>
                            ))
                        }

                    </li>

                    <li className="selfAssessment">
                        <div className="title">自我评价</div>
                        <TextArea autoSize placeholder="请输入自我评价" value={selfAssessment} onChange={this.handleSelfAssessmentChange} />
                    </li>

                    <li className="abilities">
                        <div className="title">专业技能<Button type="link" onClick={() => this.addItem('abilities')}>新增选项</Button></div>
                        {
                            abilities.map((item, index) => (
                                <div key={index} className={'bg-' + index % 2}>
                                    <Text type="warning">技能名称:</Text>
                                    <Input placeholder="请输入技能名称" value={item.key} onChange={(e) => this.handleItemChange('abilities', index, 'key', e)} />
                                    <div>技能描述: {urlTip}</div>
                                    <TextArea autoSize placeholder="请输入技能描述" value={item.detail} onChange={(e) => this.handleItemChange('abilities', index, 'detail', e)} />
                                    <Button type="link" onClick={() => this.removeItem(index, 'abilities')}>删除选项</Button>
                                </div>
                            ))
                        }
                    </li>

                    <li className="experiences">
                        <div className="title">工作经历<Button type="link" onClick={() => this.addItem('experiences')}>新增选项</Button></div>

                        {
                            experiences.map((item, index) => (
                                <div key={index} className={'bg-' + index % 2}>
                                    <Text type="warning">公司名称:</Text>
                                    <Input placeholder="请输入公司名称" value={item.companyName} onChange={(e) => this.handleItemChange('experiences', index, 'companyName', e)} />
                                    <div>职位:</div>
                                    <Input placeholder="请输入职位" value={item.position} onChange={(e) => this.handleItemChange('experiences', index, 'position', e)} />
                                    <div>工作时间:</div>
                                    <Input placeholder="请输入开始时间" value={item.time[0]} style={{ width: 150, marginRight: 30 }} onChange={(e) => this.handleExperiencesTimeChage2(index, 0, e)} />
                                    <Input placeholder="请输入结束时间" value={item.time[1]} style={{ width: 150 }} onChange={(e) => this.handleExperiencesTimeChage2(index, 1, e)} />
                                    {/* <RangePicker defaultValue={[item.time[0] ? moment(item.time[0], dateFormat) : null, item.time[1] ? moment(item.time[1], dateFormat) : null]} onChange={(date, dateString) => this.handleExperiencesTimeChage(index, dateString)} /> */}
                                    <div>描述: {urlTip}</div>
                                    <TextArea autoSize placeholder="请输入描述" value={item.detail} onChange={(e) => this.handleItemChange('experiences', index, 'detail', e)} />
                                    <Button type="link" onClick={() => this.removeItem(index, 'experiences')}>删除选项</Button>
                                </div>

                            ))
                        }
                    </li>

                    <li className="projects">
                        <div className="title">项目经验<Button type="link" onClick={() => this.addItem('projects')}>新增选项</Button></div>
                        {
                            projects.map((item, index) => (
                                <div key={index} className={'bg-' + index % 2}>
                                    <Text type="warning">项目名称:</Text>
                                    <Input placeholder="请输入项目名称" value={item.projectName} onChange={(e) => this.handleItemChange('projects', index, 'projectName', e)} />
                                    <div>关键词<Button type="link" onClick={() => this.addProjectsKeyWord(index)}>新增关键词</Button></div>
                                    {
                                        item.keyWord.map((keyWord, i) => (
                                            <a key={i} href="javacript:void(0);" className="keyWord">
                                                <Input style={{ width: 100, marginRight: 10 }} placeholder="请输入关键词" value={keyWord} onChange={(e) => { this.handleProjectsKeyWordChange(index, i, e) }} />
                                                <span onClick={() => this.removeProjectsKeyWord(index, i)} className="keyWord-icon">X</span>
                                            </a>
                                        ))
                                    }
                                    <div>描述: {urlTip}</div>
                                    <TextArea autoSize placeholder="请输入描述" value={item.detail} onChange={(e) => this.handleItemChange('projects', index, 'detail', e)} />
                                    <Button type="link" onClick={() => this.removeItem(index, 'projects')}>删除选项</Button>
                                </div>

                            ))
                        }
                    </li>

                    <li className="demos">
                        <div className="title">个人demo<Button type="link" onClick={() => this.addItem('demos')}>新增选项</Button></div>
                        {
                            demos.map((item, index) => (
                                <div key={index} className={'bg-' + index % 2}>
                                    <Text type="warning">demo名称:</Text>
                                    <Input placeholder="请输入demo名称" value={item.demoName} onChange={(e) => this.handleItemChange('demos', index, 'demoName', e)} />
                                    <div>描述: {urlTip}</div>
                                    <TextArea autoSize placeholder="请输入描述" value={item.detail} onChange={(e) => this.handleItemChange('demos', index, 'detail', e)} />
                                    <Button type="link" onClick={() => this.removeItem(index, 'demos')}>删除选项</Button>
                                </div>
                            ))
                        }
                    </li>

                    <li className="edus">
                        <div className="title">教育经历<Button type="link" onClick={() => this.addItem('edus')}>新增选项</Button></div>
                        {
                            edus.map((item, index) => (
                                <div key={index} className={'bg-' + index % 2}>
                                    <Text type="warning">学校名称:</Text>
                                    <Input placeholder="请输入学校名称" value={item.school} onChange={(e) => this.handleItemChange('edus', index, 'school', e)} />
                                    <div>教育时间:</div>
                                    <RangePicker defaultValue={[item.time[0] ? moment(item.time[0], dateFormat) : null, item.time[1] ? moment(item.time[1], dateFormat) : null]} onChange={(date, dateString) => this.handleEdusTimeChage(index, dateString)} />
                                    <div>学历/学位:</div>
                                    <Input placeholder="请输入学历/学位名称" value={item.degree} onChange={(e) => this.handleItemChange('edus', index, 'degree', e)} />
                                    <Button type="link" onClick={() => this.removeItem(index, 'edus')}>删除选项</Button>
                                </div>
                            ))
                        }
                    </li>

                    <li className="certificates">
                        <div className="title">证书<Button type="link" onClick={() => this.addItem('certificates')}>新增选项</Button></div>
                        {
                            certificates.map((item, index) => (
                                <div key={index} className={'bg-' + index % 2}>
                                    <Text type="warning">证书名称:</Text>
                                    <Input placeholder="请输入证书名称" value={item.certificateName} onChange={(e) => this.handleItemChange('certificates', index, 'certificateName', e)} />
                                    <div>获得时间:</div>
                                    <Input placeholder="请输入获得时间" value={item.time} onChange={(e) => this.handleItemChange('certificates', index, 'time', e)} />
                                    <Button type="link" onClick={() => this.removeItem(index, 'certificates')}>删除选项</Button>
                                </div>
                            ))
                        }
                    </li>

                    <li className="wordUrl">
                        <div className="title">word简历地址:</div>
                        <Input placeholder="请输入word简历地址" value={wordUrl} onChange={this.handleWordUrlChange} />
                    </li>

                    <li className="pdfUrl">
                        <div className="title">pdf简历地址:</div>
                        <Input placeholder="请输入pdf简历地址" value={pdfUrl} onChange={this.handlePdfUrlChange} />
                    </li>
                </ul>
                <Button onClick={() => this.submit(1)} type="primary" style={{marginRight: 10}}>提交</Button>
                <Button onClick={() => this.submit(0)} type="danger">暂存</Button>
            </Card>
        )
    }
}
